<template>
  <view>
    <van-cell-group>
      <van-field label="小区" right-icon="close" @click-icon="clearContent('area')" @click-input="getVillageList(1)" readonly required :value="data.villageName" placeholder="请选择小区" />
      <van-field
        right-icon="close"
        @click-icon="clearContent('server')"
        label="服务模版"
        @click-input="
          () => {
            if (data.serverModelList.length > 0) {
              data.serverModelShow = true;
            } else {
              showToast('暂无服务模版');
            }
          }
        "
        readonly
        required
        :value="data.serverModelName"
        placeholder="请选择服务模版"
      />
      <van-field
        right-icon="close"
        @click-icon="clearContent('promotion')"
        label="推广模版"
        @click-input="
          () => {
            if (data.promoteModelList.length > 0) {
              data.promotionModelShow = true;
            } else {
              showToast('暂无推广模版');
            }
          }
        "
        readonly
        required
        :value="data.promoteModelName"
        placeholder="请选择推广模版"
      />
    </van-cell-group>
    <view class="fixed w-full c-pd" :style="{ bottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button color="#ffc300" block @click="submitChange">确认提交</van-button>
    </view>
    <van-popup :show="data.areaShow" position="bottom" custom-style="height: 50%">
      <view class="flex items-center">
        <view class="flex-1 text-align-center" @click="onAreaCancel">取消</view>
        <van-search
          :value="data.keyWord"
          placeholder="请输入小区"
          @search="getVillageList"
          @change="
            (e: any) => {
              data.keyWord = e.detail;
            }
          "
        />
        <view
          class="flex-1 text-align-center"
          @click="
            () => {
              data.areaShow = false;
              if (!data.villageId) {
                data.villageId = data.areaList[0].id;
                data.villageName = data.areaList[0].name;
              }
              getServerModelList();
            }
          "
          >完成</view
        >
      </view>
      <van-picker :show-toolbar="false" :default-index="0" value-key="name" :columns="data.areaList" @change="onAreaChange" title="选择小区" />
    </van-popup>
    <van-popup :show="data.serverModelShow" position="bottom" custom-style="height: 50%">
      <van-picker show-toolbar confirm-button-text="确认" cancel-button-text="取消" value-key="modelName" :columns="data.serverModelList" @confirm="onServerChange" @cancel="onServerCancel" title="选择服务模版" />
    </van-popup>
    <van-popup :show="data.promotionModelShow" position="bottom" custom-style="height: 50%">
      <van-picker show-toolbar confirm-button-text="确认" cancel-button-text="取消" value-key="modelName" :columns="data.promoteModelList" @confirm="onPromotionChange" @cancel="onPromotionCancel" title="选择推广模版" />
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import UserRequest from '@/request/userRequest';
import useToast from '@/hooks/useToast';
import { navigate } from '@/utils/navigate';
import { useAppStore } from '@/store';

interface IData {
  userId: number;
  villageId?: number;
  serverModelId?: number;
  promoteModelId?: number;
  areaList: IResidentialAddressListRes[];
  areaShow: boolean;
  serverModelShow: boolean;
  promotionModelShow: boolean;
  villageName: string;
  promoteModelName: string;
  serverModelName: string;
  serverModelList: IServerModelList[];
  promoteModelList: IPromotionModelList[];
  keyWord: string;
}

const data = reactive<IData>({
  userId: 0,
  areaList: [],
  serverModelList: [],
  promoteModelList: [],
  promoteModelName: '',
  villageName: '',
  serverModelName: '',
  villageId: undefined,
  serverModelId: undefined,
  promoteModelId: undefined,
  areaShow: false,
  serverModelShow: false,
  promotionModelShow: false,
  keyWord: '',
});

const store = useAppStore();

const { showToast } = useToast();

onLoad((options) => {
  if (!options) return;
  data.userId = options.userId;
});

const getVillageList = (num?: number) => {
  UserRequest.AreaListIdName({ hasLoading: true, name: data.keyWord }).then((res) => {
    data.areaList = res.data;
    if (num) {
      if (data.areaList.length > 0) {
        data.areaShow = true;
      } else {
        showToast('暂无小区');
      }
    }
  });
};

const getServerModelList = () => {
  UserRequest.GetServerModel({ outUserId: data.userId, villageId: data.villageId, hasLoading: true }).then((res) => {
    data.serverModelList = res.data;
  });
};

const getPromotionModelList = () => {
  UserRequest.promotionModelList({ outUserId: data.userId, villageId: data.villageId, serverModelId: data.serverModelId, hasLoading: true }).then((res) => {
    data.promoteModelList = res.data;
  });
};

const onAreaChange = (e: any) => {
  data.villageName = e.detail.value.name;
  data.villageId = e.detail.value.id;
};
const onAreaCancel = () => {
  data.areaShow = false;
};

const onServerChange = (e: any) => {
  data.serverModelName = e.detail.value.modelName;
  data.serverModelId = e.detail.value.modelId;
  data.serverModelShow = false;
  getPromotionModelList();
};
const onServerCancel = () => {
  data.serverModelShow = false;
};

const onPromotionChange = (e: any) => {
  data.promoteModelName = e.detail.value.modelName;
  data.promoteModelId = e.detail.value.promoteModelId;
  data.promotionModelShow = false;
};
const onPromotionCancel = () => {
  data.promotionModelShow = false;
};

const clearContent = (type: string) => {
  switch (type) {
    case 'area':
      data.villageName = '';
      data.villageId = undefined;
      data.serverModelName = '';
      data.serverModelId = undefined;
      data.promoteModelName = '';
      data.promoteModelId = undefined;
      data.serverModelList = [];
      data.promoteModelList = [];
      break;
    case 'server':
      data.serverModelName = '';
      data.serverModelId = undefined;
      data.promoteModelName = '';
      data.promoteModelId = undefined;
      data.promoteModelList = [];
      break;
    case 'promotion':
      data.promoteModelName = '';
      data.promoteModelId = undefined;
      break;
  }
};

const submitChange = () => {
  const { promoteModelId, serverModelId, userId, villageId } = data;
  if (!promoteModelId || !serverModelId || !villageId) {
    showToast('请选择完整信息');
    return false;
  }
  UserRequest.ApplyCode({
    promoteModelId: promoteModelId,
    serverModelId: serverModelId,
    userId: userId,
    villageId: villageId,
  }).then((res) => {
    if (res.status === 0) {
      showToast('操作成功', 'success');
      setTimeout(() => {
        navigate({ url: '', type: 'navigateBack' });
      }, 1000);
    }
  });
};
</script>
